package excel

import (
	"fmt"
	"gitee.com/dreamwood/ez-go/ez"
	"github.com/xuri/excelize/v2"
	"path"
	"regexp"
	"strconv"
	"time"
)

type Importer struct {
	File  *excelize.File
	Sheet string
}

func NewImporter() *Importer {
	return &Importer{
		Sheet: "Sheet1",
	}
}

func (i *Importer) LoadFile(filePath string) error {
	filePath = "." + path.Clean(filePath)
	f, e := excelize.OpenFile(filePath)
	if ez.Try(e) {
		return e
	}
	i.File = f
	return nil
}

func (i *Importer) GetText(cell string, opts ...excelize.Options) string {
	got, e := i.File.GetCellValue(i.Sheet, cell, opts...)
	if ez.Try(e) {
		return e.Error()
	}
	return got
}

func (i *Importer) GetInt(cell string, opts ...excelize.Options) int64 {
	str := i.GetText(cell, opts...)
	got, e := strconv.ParseInt(str, 10, 64)
	if ez.Try(e) {
		return 0
	}
	return got
}

func (i *Importer) GetFloat(cell string, opts ...excelize.Options) float64 {
	str := i.GetText(cell, opts...)
	got, e := strconv.ParseFloat(str, 10)
	if ez.Try(e) {
		return 0
	}
	return got
}

//func (i *Importer) GetPic(cell string) string {
//	filename, raw, e := i.File.GetPicture(i.Sheet, cell)
//	if ez.Try(e) {
//		return ""
//	}
//	rnd := tools.CreateRandString(10)
//	url := fmt.Sprintf("/static/excel/%s/%s_%s%s", tools.GetDateYMD(), tools.GetDateYMDHIS("", "", "_"), rnd, path2.Ext(filename))
//	path := fmt.Sprintf("./%s", url)
//	tools.CreateFile(path, raw)
//	return url
//}

func (i *Importer) GetTime(cell string, opts ...excelize.Options) *time.Time {
	str := i.GetText(cell, opts...)
	//1987年8月15日
	//19870815
	//1987/08/15
	//1987.08.15
	//1987.08.15
	//匹配年
	matchYear := "(?P<year>[0-9]{4})"
	matchMonth := "(?P<month>[0-1]{0,1}[0-9])?"
	matchDay := "(?P<day>[0-3]{0,1}[0-9])?"
	//匹配时间
	matchTime := `(?P<time>\s([0-2]{0,1}[0-9]):([0-5]{0,1}[0-9]))?`
	pattern := fmt.Sprintf("%s[^0-9]{0,1}%s[^0-9]{0,1}%s%s", matchYear, matchMonth, matchDay, matchTime)
	reg := regexp.MustCompile(pattern)
	if reg == nil {
		return nil
	}
	matches := reg.FindAllStringSubmatch(str, -1)
	y := ""
	m := ""
	d := ""
	h := ""
	min := ""
	if len(matches) == 1 && len(matches[0]) == 7 {
		y = matches[0][1]
		m = matches[0][2]
		if len(m) == 0 {
			m = "01"
		}
		if len(m) == 1 {
			m = "0" + m
		}
		d = matches[0][3]
		if len(d) == 0 {
			d = "01"
		}
		if len(d) == 1 {
			d = "0" + d
		}
		h = matches[0][5]
		if len(h) == 0 {
			h = "00"
		}
		if len(h) == 1 {
			h = "0" + h
		}
		min = matches[0][6]
		if len(min) == 0 {
			min = "00"
		}
		if len(min) == 1 {
			min = "0" + min
		}
	} else {
		return nil
	}
	date := fmt.Sprintf("%s-%s-%sT%s:%s:00+08:00", y, m, d, h, min)

	t, e := time.Parse(time.RFC3339, date)
	if ez.Try(e) {
		return nil
	}
	return &t
}
